import React, { useState, Dispatch, SetStateAction } from 'react';
interface AppStateProps {
    username: string;
    shoppingCart: {
        items: {
            id: number;
            name: string;
        }[]
    }
}
const defaultContextValue: AppStateProps = {
    username: 'dva',
    shoppingCart: {
        items: []
    }
}

export const AppContext = React.createContext(defaultContextValue);
// export const AppSetStateContext = React.createContext<React.Dispatch<React.SetStateAction<AppStateProps>> | undefined>(undefined);
export const AppSetStateContext = React.createContext<Dispatch<SetStateAction<AppStateProps>>>(()=>{})

export const AppStateProvider: React.FC = props => {
    const [state, setState] = useState(defaultContextValue);
    return (
        <AppContext.Provider value={state}>
            <AppSetStateContext.Provider value={setState}>
                {
                    props.children //props.children 表示被Provider标签包裹的子组件，子组件可以通过组件树向离自身追接近的Provider获取context数据
                }
            </AppSetStateContext.Provider>
        </AppContext.Provider>
    )
}

